package com.example.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * <b>TODO . </b>
 *
 * @author yangyl11
 * @version 1.0.0
 * @date 2020/11/26
 * @since JDK 1.8
 */
@Component
public class TokenFilter extends ZuulFilter {

	/**
	 * pre：可以在请求被路由之前调用
	 * route：在路由请求时候被调用
	 * post：在route和error过滤器之后被调用
	 * error：处理请求时发生错误时被调用
	 * @return
	 */
	@Override
	public String filterType() {

		return "pre";
	}

	@Override
	public int filterOrder() {

		return 0;
	}

	@Override
	public boolean shouldFilter() {

		return true;
	}

	@Override
	public Object run() throws ZuulException {

		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		Object token = request.getParameter("token");

		if (token == null) {

			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);//401表示无权限
			try {
				ctx.getResponse().getWriter().write("token is empty");
			} catch (Exception e) {
			}
			return null;
		}

		return null;
	}
}
